﻿using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Spire.Pdf;
using System;
using Spire.Doc;

namespace Wpf_Examples.Views
{
    /// <summary>
    /// LoadPDFAndWordWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoadPDFAndWordWindow : Window
    {
        public LoadPDFAndWordWindow()
        {
            InitializeComponent();

            //LoadPdf("C:\\Users\\Administrator\\Desktop\\四川省考备考思路梳理.pdf");

            LoadWord("C:\\Users\\Administrator\\Desktop\\测试文档.docx");
        }


        private void LoadWord(string filePath)
        {
            // 将 Word 文档转换为 HTML
            Document document = new Document();
            document.LoadFromFile(filePath);
            string htmlPath = Path.ChangeExtension(filePath, ".html");
            document.SaveToFile(htmlPath, Spire.Doc.FileFormat.Html);

            // 使用 WebView2 控件加载 HTML
            wordWebView.Source = new Uri(htmlPath);
        }

        private void LoadPdf(string filePath)
        {
            PdfDocument pdf = new PdfDocument(filePath);
            var bitmap = pdf.SaveAsImage(0); // 加载第一页
            pdfImage.Source = ConvertToImageSource(bitmap);

        }

        public static ImageSource ConvertToImageSource(System.Drawing.Image image)
        {
            using (var stream = new MemoryStream())
            {
                image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze(); // 使位图图像线程安全
                return bitmapImage;
            }
        }
    }
}
